<?php
  include ('header.php');
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title><?php echo $titles['edit_all_inventory'] ?></title>	

</head>

<?php

$fieldseparator = ";";
$lineseparator = "\n";
if(isset($_FILES['filename']) && $_FILES['filename'] ){
$csvfile = $_FILES['filename'][tmp_name];
$error=0;

if(!file_exists($csvfile)) {
$error="File not found. Make sure you specified the correct path";
}
$file = fopen($csvfile,"r");

if(!$file) {
$error="Error opening data file";
}

$size = filesize($csvfile);
#

if(!$size) {
$error= "File is empty";
}

if(!$error){
$csvcontent = fread($file,$size);
fclose($file);
$lines = 0;
$queries = "";
$linearray = array();
$line_count=0;
 
foreach(split($lineseparator,$csvcontent) as $line) {

$lines++;

$line = trim($line," \t");
$line = str_replace("\r","",$line);

$line = str_replace("'","\'",$line);
$line=iconv("CP1251","UTF-8",$line);

$linearray = explode($fieldseparator,$line);



if($lines>1 && $linearray[8]>''){	
$sql2="SELECT * FROM inventory_type where type_name='".$linearray[15]."'";  
$process2=mysql_query($sql2, $db);
$row2 = mysql_fetch_array($process2);
$linearray[15]=$row2[type_id];
//echo $sql2;

$sql2="SELECT * FROM auditories where auditory_name='".$linearray[14]."'";  
    $process2=mysql_query($sql2, $db);
	$row2 = mysql_fetch_array($process2);
$linearray[14]=$row2[auditory_id];

//echo $sql2."<br>";
	$sql2="SELECT * FROM item_status where status_name='".$linearray[13]."'";  
    $process2=mysql_query($sql2, $db);
	$row2 = mysql_fetch_array($process2);
	$linearray[13]=$row2[status_id];
	
$sql2="SELECT * FROM users where real_name='".$linearray[12]."'";  
    $process2=mysql_query($sql2, $db);
	$row2 = mysql_fetch_array($process2);
	$linearray[12]=$row2[id];
//echo $sql2."<br>";
$linemysql = implode("','",$linearray);
												//0			//1				//2				//3			 //4			//5   			//6			//7			//8			//9		//10		//11   		//12		//13			//14			//15			
	$query = "REPLACE into all_inventory  (`item_name`, `another_name`, `nom_number`, `sn_internal`, `sub_rah`, `date_open`, `ed_code`, `ed_type`, `inv_numb`, `count`, `code`, `one_cost`, `manage`, `status`, `auditory`, `item_type`) 
values('$linemysql');";
	$queries .= $query . "\n";
	mysql_query($queries , $db);
	}
	//echo $query."<br>";
	$line_count++;
}
echo "<script>alert('Успішно імпортовано  $line_count запис(а/ів)')</script>";


}
else {
echo "<script>alert('УВАГА ".$error."')</script>";}
}
?>


<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data">
<table  class="import_xls" >
<tr>
<td width='100%' class="import_xls">
Завантажити данні з файлу: 
<input type="file" name="filename"> 
<input type="submit" value="<?php echo $texts[upload]?>">
</tr>
</table>
</form>
</body>
<?php
  include ('footer.php');
?>
</html>